package com.im.service.contract.smo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.im.MDA;
import com.im.service.contract.dao.IContractClauseOperDAO;
import com.im.service.contract.dao.IContractItemChangeOperDAO;
import com.im.service.contract.dao.IContractItemChangeQueryDAO;
import com.im.service.contract.dao.IContractItemOperDAO;
import com.im.service.contract.dao.IContractItemQueryDAO;
import com.im.service.contract.dao.IContractOperDAO;
import com.im.service.dto.BaseException;
import com.im.service.dto.Contract;
import com.im.service.dto.ContractClause;
import com.im.service.dto.ContractItemChange;
import com.im.service.dto.FileUpload;
import com.im.service.folderManage.dao.IFolderManageOperDAO;
import com.im.service.model.ContractAndItemVo;
import com.im.util.CommonUtil;
import com.im.util.DateUtil;
import com.im.util.JsonUtil;
import com.im.util.ReturnsUtil;
import com.im.util.StringUtil;
import com.im.viewmodel.fundPlan.FileVo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ContractOperSMOImpl implements IContractOperSMO{
	private static final Logger logger = LogManager.getLogger(ContractOperSMOImpl.class);
	@Autowired
	private IContractOperDAO contractOperDAO;
	@Autowired
	private IContractItemOperDAO contractItemOperDAO;
	@Autowired
	private IContractClauseOperDAO contractclauseOperDAO;
	@Autowired
	private IContractItemQueryDAO contractItemQueryDAO;
	@Autowired
	private IContractItemChangeOperDAO contractItemChangeOperDAO;
	@Autowired
	private IContractItemChangeQueryDAO contractItemChangeQueryDAO;
	@Autowired
	private IFolderManageOperDAO folderManageOperDAO;

	@Autowired
	private IContractQuerySMO contractQuerySMO;
	@Override
	public String saveOrUpdateContract(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		Map classMap = new HashMap();
		classMap.put("performanceFiles", FileVo.class);
		classMap.put("expectFiles", FileVo.class);
		classMap.put("electronFiles", FileVo.class);
		classMap.put("meetFiles", FileVo.class);
		classMap.put("delFiles", FileVo.class);
		Contract contract = JsonUtil.jsonToBean(jsonStr, Contract.class, classMap);
		if(contract.getTotal() == null){
			throw new BaseException("中标金额必填！");
		}
//		contract.setStatusCd(MDA.CONTRACT_STATUS_CD_SIGNED.toString());// 合同默认 20 已签订 modify by xuwb 20180716
		Boolean newflag = !StringUtil.isEmpty(contract.getContractId());
		if (newflag) {
			contract.setContractCode(null);
			contractOperDAO.updateContract(contract);
		} else {
			contract.setContractId(UUID.randomUUID().toString());
			contractOperDAO.insertContract(contract);
		}
		// 履约保函保存
		if (contract.getPerformanceFiles() != null) {
			List<FileVo> list = contract.getPerformanceFiles();
			for (FileVo perform : list) {
				if (StringUtils.isEmpty(perform.getUploadId())) {
				FileUpload fileUploadInfo = new FileUpload();
				String uploadType = "";
				if (!"".equals(perform.getAttachSuffix())) {
					uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(perform.getAttachSuffix().toLowerCase());
				}
				String uploadId = UUID.randomUUID().toString();
				fileUploadInfo.setUploadId(uploadId);
				fileUploadInfo.setUploadName(perform.getAttachFullName());
				fileUploadInfo.setUploadObjType("180");
				fileUploadInfo.setUploadObjId(contract.getContractId());
				fileUploadInfo.setUploadType(uploadType);
				fileUploadInfo.setFileSuffix(perform.getAttachSuffix());
				fileUploadInfo.setFileAttr("10");
				fileUploadInfo.setFileType("10");
				fileUploadInfo.setUploadSize(Long.valueOf(perform.getAttachSize()));
				fileUploadInfo.setFilePath(perform.getAttachPath());
				String uploadDate = "";
				if(perform.getUploadDt() != null && perform.getUploadDt().length() > 0){
					uploadDate = perform.getUploadDt();
				}else{
					uploadDate = DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A);
				}
				fileUploadInfo.setUploadDate(uploadDate);
					folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
				}
			}
		}
		// 预付款保函保存
		if (contract.getExpectFiles() != null) {
			List<FileVo> list = contract.getExpectFiles();
			for (FileVo expect : list) {
				if (StringUtils.isEmpty(expect.getUploadId())) {
				FileUpload fileUploadInfo = new FileUpload();
				String uploadType = "";
				if (!"".equals(expect.getAttachSuffix())) {
					uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(expect.getAttachSuffix().toLowerCase());
				}
				String uploadId = UUID.randomUUID().toString();
				fileUploadInfo.setUploadId(uploadId);
				fileUploadInfo.setUploadName(expect.getAttachFullName());
				fileUploadInfo.setUploadObjType("190");
				fileUploadInfo.setUploadObjId(contract.getContractId());
				fileUploadInfo.setUploadType(uploadType);
				fileUploadInfo.setFileSuffix(expect.getAttachSuffix());
				fileUploadInfo.setFileAttr("10");
				fileUploadInfo.setFileType("10");
				fileUploadInfo.setUploadSize(Long.valueOf(expect.getAttachSize()));
				fileUploadInfo.setFilePath(expect.getAttachPath());
				fileUploadInfo.setUploadDate(expect.getUploadDt());
					folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
				}
			}
		}
		
		// 电子合同
		if (contract.getElectronFiles() != null) {
			List<FileVo> list = contract.getElectronFiles();
			for (FileVo expect : list) {
				if (StringUtils.isEmpty(expect.getUploadId())) {
				FileUpload fileUploadInfo = new FileUpload();
				String uploadType = "";
				if (!"".equals(expect.getAttachSuffix())) {
					uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(expect.getAttachSuffix().toLowerCase());
				}
				String uploadId = UUID.randomUUID().toString();
				fileUploadInfo.setUploadId(uploadId);
				fileUploadInfo.setUploadName(expect.getAttachFullName());
				fileUploadInfo.setUploadObjType("200");
				fileUploadInfo.setUploadObjId(contract.getContractId());
				fileUploadInfo.setUploadType(uploadType);
				fileUploadInfo.setFileSuffix(expect.getAttachSuffix());
				fileUploadInfo.setFileAttr("10");
				fileUploadInfo.setFileType("10");
				fileUploadInfo.setUploadSize(Long.valueOf(expect.getAttachSize()));
				fileUploadInfo.setFilePath(expect.getAttachPath());
				fileUploadInfo.setUploadDate(expect.getUploadDt());
					folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
				}
			}
		}
		
		// 会议纪要
		if (contract.getMeetFiles() != null) {
			List<FileVo> list = contract.getMeetFiles();
			for (FileVo expect : list) {
				if (StringUtils.isEmpty(expect.getUploadId())) {
				FileUpload fileUploadInfo = new FileUpload();
				String uploadType = "";
				if (!"".equals(expect.getAttachSuffix())) {
					uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(expect.getAttachSuffix().toLowerCase());
				}
				String uploadId = UUID.randomUUID().toString();
				fileUploadInfo.setUploadId(uploadId);
				fileUploadInfo.setUploadName(expect.getAttachFullName());
				fileUploadInfo.setUploadObjType("210");
				fileUploadInfo.setUploadObjId(contract.getContractId());
				fileUploadInfo.setUploadType(uploadType);
				fileUploadInfo.setFileSuffix(expect.getAttachSuffix());
				fileUploadInfo.setFileAttr("10");
				fileUploadInfo.setFileType("10");
				fileUploadInfo.setUploadSize(Long.valueOf(expect.getAttachSize()));
				fileUploadInfo.setFilePath(expect.getAttachPath());
				fileUploadInfo.setUploadDate(expect.getUploadDt());
					folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
				}
			}
		}
				
		// 删除文件
		if (contract.getDelFiles() != null && contract.getDelFiles().size() > 0) {
			List<FileVo> dellist = contract.getDelFiles();
			for (int i = 0; i < dellist.size(); i++) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("uploadId", dellist.get(i).getUploadId());
				folderManageOperDAO.delFileUpload(param);
			}
		}
		ContractClause contractClause = new ContractClause();
		contractClause.setContractId(contract.getContractId());
		contractClause.setStatuscd(0);
		contractClause.setContractClauseName(contract.getContractClauseName());

		boolean  existContractClause= contractQuerySMO.existContractClause(contract.getContractId());
		if (existContractClause) {
			contractclauseOperDAO.updateContractClause(contractClause);
		} else {
			contractClause.setContractClauseId(UUID.randomUUID().toString());
			contractClause.setContractClauseCode(CommonUtil.generateShortUuid());
			contractclauseOperDAO.insertContractClause(contractClause);
		}
		return ReturnsUtil.returnSuccess(new JSONObject()).toString();
	}

	@Override
	public String saveOrUpdateContractItem(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			ContractAndItemVo contractItem = JsonUtil.jsonToBean(jsonStr, ContractAndItemVo.class);
			Boolean newflag = !StringUtil.isEmpty(contractItem.getContractItemId());
			if (newflag) {
				contractItem.setUnpaid(contractItem.getItemTotal());
				contractItem.setStatusCd(MDA.CONTRACT_ITEM_CHANGE_STATUS_CD_PENDING.toString());
				contractItemOperDAO.updateContractItem(contractItem);
			} else {
				contractItem.setContractItemId(UUID.randomUUID().toString());
				contractItem.setConItemId(UUID.randomUUID().toString());
				contractItem.setContractItemObj("obj");// 待确定
				contractItem.setContractItemType("10");
				contractItem.setSeriveCharge(new BigDecimal(0));
				contractItem.setPayment(new BigDecimal(0));
				contractItem.setPaymentRatio(new BigDecimal(0));
				contractItem.setPrepay(new BigDecimal(0));
				contractItem.setUnpaid(contractItem.getItemTotal());
				contractItem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_PENDING.toString());
				contractItem.setContractItemCode(CommonUtil.generateShortUuid());
				contractItem.setDataType(MDA.CONTRACT_ITEM_DATA_TYPE_ORIGINAL);
				contractItemOperDAO.insertContractItem(contractItem);
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("新增或修改合同分项失败", e).toString();
		}
	}

	@Override
	public String saveOrUpdateContractIteChange(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取入参时：";
			String conItemId = JsonUtil.getNotNullStringFromJSON(jsonObj, "conItemId", errorMsg);
			String contractItemId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractItemId", errorMsg);
			String contractClauseId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractClauseId", errorMsg);
			String contItemChangeId = JsonUtil.getStringFromJSON(jsonObj, "contItemChangeId", errorMsg);
			String optype = JsonUtil.getNotNullStringFromJSON(jsonObj, "optype", errorMsg);
			String contractItemName = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractItemName", errorMsg);
			String unitPrice = JsonUtil.getNotNullStringFromJSON(jsonObj, "unitPrice", errorMsg);
			String description = JsonUtil.getNotNullStringFromJSON(jsonObj, "description", errorMsg);
			Long amount = JsonUtil.getLongFromJSON(jsonObj, "amount", errorMsg);
			Integer status = JsonUtil.getIntegerFromJSON(jsonObj, "status", errorMsg);
			BigDecimal itemTotal = new BigDecimal(JsonUtil.getIntegerFromJSON(jsonObj, "itemTotal", errorMsg));
			BigDecimal otherCharge = new BigDecimal(JsonUtil.getIntegerFromJSON(jsonObj, "otherCharge", errorMsg));
			ContractItemChange changevo = new ContractItemChange();
			if ("0".equals(optype)) {// 新增
				changevo.setContractItemId(UUID.randomUUID().toString());
				// changevo.setContractItemId(contractItemId);
				changevo.setContractClauseId(contractClauseId);
				changevo.setContractItemCode(CommonUtil.generateShortUuid());
				changevo.setContractItemName(contractItemName);
				changevo.setContractItemType("10");
				changevo.setContractItemObj("obj");
				changevo.setAmount(amount);
				changevo.setUnitPrice(unitPrice);
				changevo.setTotal(itemTotal);
				changevo.setOtherCharge(otherCharge);
				changevo.setSeriveCharge(new BigDecimal(0));
				changevo.setContItemChangeId(UUID.randomUUID().toString() + "_1");
				changevo.setStatusCd(MDA.CONTRACT_ITEM_CHANGE_STATUS_CD_PENDING.toString());
				changevo.setDescription(description);
				changevo.setDataType(MDA.CONTRACT_ITEM_DATA_TYPE_MOFIFY);
				contractItemChangeOperDAO.insertContractItemChange(changevo);
				/*
				 * ContractAndItemVo itemVo = new ContractAndItemVo();
				 * itemVo.setConItemId(conItemId);
				 * itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_CHANGING.
				 * toString()); contractItemOperDAO.updateContractItem(itemVo);
				 */
			} else if ("1".equals(optype)) {// 修改
				// if (status == 30) {
					if (StringUtil.isBlank(contItemChangeId)) {// 第一次修改分项数据
						ContractAndItemVo oldvo = new ContractAndItemVo();
						oldvo.setConItemId(conItemId);
						Map<String, Object> param = new HashMap<String, Object>();
						param.put("contractItem", oldvo);
						oldvo = contractItemQueryDAO.queryContractItemDetail(param);
						
						changevo.setContractItemId(contractItemId);
						changevo.setContractClauseId(oldvo.getContractClauseId());
						changevo.setContractItemCode(oldvo.getContractItemCode());
						changevo.setContractItemName(oldvo.getContractItemName());
						changevo.setContractItemType(oldvo.getContractItemType());
						changevo.setContractItemObj("obj");
						changevo.setSeriveCharge(new BigDecimal(0));
						changevo.setContItemChangeId(UUID.randomUUID().toString() + "_2");
						changevo.setStatusCd(MDA.CONTRACT_ITEM_CHANGE_STATUS_CD_PENDING.toString());
						changevo.setDataType(MDA.CONTRACT_ITEM_DATA_TYPE_MOFIFY);
						changevo.setAmount(amount);
						changevo.setUnitPrice(unitPrice);
						changevo.setTotal(itemTotal);
						changevo.setOtherCharge(otherCharge);
						changevo.setDescription(description);
						changevo.setContractItemName(contractItemName);
						// 保存分项变更记录
						contractItemChangeOperDAO.insertContractItemChange(changevo);

					ContractAndItemVo itemVo = new ContractAndItemVo();
					itemVo.setConItemId(conItemId);
					itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_CHANGING.toString()); //
					// 更新分项状态
					contractItemOperDAO.updateContractItem(itemVo);

					} else {// 多次修改已添加的分项变更
						changevo.setContItemChangeId(contItemChangeId);
						changevo.setAmount(amount);
						changevo.setUnitPrice(unitPrice);
						changevo.setTotal(itemTotal);
						changevo.setOtherCharge(otherCharge);
						changevo.setDescription(description);
						changevo.setContractItemName(contractItemName);
						contractItemChangeOperDAO.updateContractItemChange(changevo);
					}
				// }
					/*
				 * // 待审核和审核未通过的变更 if (StringUtil.isBlank(contItemChangeId)) {//
				 * 第一次修改分项数据 ContractAndItemVo oldvo = new ContractAndItemVo();
				 * oldvo.setConItemId(conItemId); Map<String, Object> param =
				 * new HashMap<String, Object>(); param.put("contractItem",
				 * oldvo); oldvo =
				 * contractItemQueryDAO.queryContractItemDetail(param);
				 * ContractItemChange changevo = new ContractItemChange();
				 * changevo.setContractItemId(contractItemId);
				 * changevo.setContractClauseId(oldvo.getContractClauseId()) ;
				 * changevo.setContractItemCode(oldvo.getContractItemCode()) ;
				 * changevo.setContractItemName(oldvo.getContractItemName()) ;
				 * changevo.setContractItemType(oldvo.getContractItemType()) ;
				 * changevo.setContractItemObj("obj");
				 * changevo.setSeriveCharge(new BigDecimal(0));
				 * changevo.setContItemChangeId(UUID.randomUUID().toString() +
				 * "_3"); changevo.setAmount(amount);
				 * changevo.setUnitPrice(unitPrice);
				 * changevo.setTotal(itemTotal);
				 * changevo.setOtherCharge(otherCharge);
				 * changevo.setDescription(description);
				 * changevo.setContractItemName(contractItemName);
				 * changevo.setStatusCd(MDA.
				 * CONTRACT_ITEM_CHANGE_STATUS_CD_PENDING.toString());
				 * changevo.setDescription(oldvo.getDescription());
				 * changevo.setDataType(MDA.CONTRACT_ITEM_DATA_TYPE_MOFIFY); //
				 * 保存原有分项冲抵记录
				 * contractItemChangeOperDAO.insertContractItemChange(
				 * changevo); ContractAndItemVo itemVo = new
				 * ContractAndItemVo(); itemVo.setConItemId(conItemId);
				 * itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_CHANGING2.
				 * toString()); contractItemOperDAO.updateContractItem(itemVo);
				 * } else {// 多次修改已添加的分项变更 ContractItemChange changevo = new
				 * ContractItemChange();
				 * changevo.setContItemChangeId(contItemChangeId);
				 * changevo.setAmount(amount); changevo.setUnitPrice(unitPrice);
				 * changevo.setTotal(itemTotal);
				 * changevo.setOtherCharge(otherCharge);
				 * changevo.setDescription(description);
				 * changevo.setContractItemName(contractItemName);
				 * contractItemChangeOperDAO.updateContractItemChange(
				 * changevo); }}
				 */
			}
			// 附件处理
			uploadFileDeal(jsonStr, "170", changevo.getContItemChangeId());
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("新增或修改合同分项失败", e).toString();
		}
	}

	public void uploadFileDeal(String inJson, String uploadObjType, String uploadObjId) {
		JSONObject jsonObject = JSONObject.fromObject(inJson);
		JSONArray jsonArray = new JSONArray();
		if (jsonObject.containsKey("addFiles"))
			jsonArray = jsonObject.getJSONArray("addFiles");
		for (int i = 0; i < jsonArray.size(); i++) {
			String fileJson = jsonArray.getString(i).toString();
			String uploadId = JsonUtil.obtainValueFromJsonObject(fileJson, "uploadId");// uploadId
			if (StringUtils.isNotBlank(uploadId)) {
				continue;// 已有记录不做新增
			}
			String uploadName = JsonUtil.obtainValueFromJsonObject(fileJson, "attachFullName");// attachFullName
			String fileSuffix = JsonUtil.obtainValueFromJsonObject(fileJson, "attachSuffix");// attachSuffix
			String fileAttr = "10";
			String fileType = "10";
			String uploadSize = JsonUtil.obtainValueFromJsonObject(fileJson, "attachSize");// attachSize
			String filePath = JsonUtil.obtainValueFromJsonObject(fileJson, "attachPath");// attachPath
			String uploadDate = JsonUtil.obtainValueFromJsonObject(fileJson, "uploadDt");// uploadDt
			String uploadType = "";
			FileUpload fileUploadInfo = new FileUpload();
			if (!"".equals(fileSuffix)) {
				uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(fileSuffix.toLowerCase());
			}
			uploadId = UUID.randomUUID().toString();
			fileUploadInfo.setUploadId(uploadId);
			fileUploadInfo.setUploadName(uploadName);
			fileUploadInfo.setUploadObjType(uploadObjType);
			fileUploadInfo.setUploadObjId(uploadObjId);
			fileUploadInfo.setUploadType(uploadType);
			fileUploadInfo.setFileSuffix(fileSuffix);
			fileUploadInfo.setFileAttr(fileAttr);
			fileUploadInfo.setFileType(fileType);
			fileUploadInfo.setUploadSize(Long.valueOf(uploadSize));
			fileUploadInfo.setFilePath(filePath);
			fileUploadInfo.setUploadDate(uploadDate);
			folderManageOperDAO.insertFileUploadInfo(fileUploadInfo);
		}
		if (jsonObject.containsKey("delFiles")) {
			JSONArray deljsonArray = jsonObject.getJSONArray("delFiles");
			if (deljsonArray.size() > 0) {
				for (int i = 0; i < deljsonArray.size(); i++) {
					JSONObject item = deljsonArray.getJSONObject(i);
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("uploadId", item.getString("uploadId"));
					folderManageOperDAO.delFileUpload(param);
				}
			}
		}

	}
	@Override
	public String importContractItem(MultipartFile file, String contractClauseId, String changeexport) {
		String filename = file.getOriginalFilename();
		Workbook workbook = null;
		try {
			if (CommonUtil.isExcel2003(filename)) {
				workbook = new HSSFWorkbook(file.getInputStream());
			} else if (CommonUtil.isExcel2007(filename)) {
				workbook = new XSSFWorkbook(file.getInputStream());
			} else {
				throw new BaseException("文件格式错误！");
			}
			// 得到第一个shell
			StringBuffer errorData = new StringBuffer();
			Sheet sheet = workbook.getSheetAt(0);
			int totalRows = sheet.getPhysicalNumberOfRows();
			List<ContractAndItemVo> importlist = new ArrayList<ContractAndItemVo>();
			for (int i = 1; i < totalRows; i++) {
				Row row = sheet.getRow(i);
				ContractAndItemVo contractItem = new ContractAndItemVo();
				contractItem.setContractClauseId(contractClauseId);
				contractItem.setContractItemId(UUID.randomUUID().toString());
				String contractItemName = CommonUtil.getValue(row.getCell(0));
				String amount = CommonUtil.getValue(row.getCell(1));
				String unitPrice = CommonUtil.getValue(row.getCell(2));
				String othercharge = CommonUtil.getValue(row.getCell(3));
				String description = CommonUtil.getValue(row.getCell(4));
				BigDecimal total = new BigDecimal(unitPrice)
						.multiply(new BigDecimal(amount)).add(new BigDecimal(othercharge));
				contractItem.setContractItemName(contractItemName);
				contractItem.setAmount(Long.valueOf(amount));
				contractItem.setUnitPrice(unitPrice);
				contractItem.setOtherCharge(new BigDecimal(othercharge));
				contractItem.setItemTotal(total);
				contractItem.setDescription(description);
				contractItem.setConItemId(UUID.randomUUID().toString());
				contractItem.setContractItemObj("obj");// 待确定
				contractItem.setContractItemType("10");
				contractItem.setSeriveCharge(new BigDecimal(0));
				contractItem.setPayment(new BigDecimal(0));
				contractItem.setPaymentRatio(new BigDecimal(0));
				contractItem.setPrepay(new BigDecimal(0));
				contractItem.setUnpaid(contractItem.getItemTotal());
				contractItem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_PENDING.toString());
				contractItem.setContractItemCode(CommonUtil.generateShortUuid());
				contractItem.setDataType(MDA.CONTRACT_ITEM_DATA_TYPE_ORIGINAL);
				importlist.add(contractItem);
			}
			if (StringUtils.isEmpty(changeexport)) {
				for (ContractAndItemVo contractAndItemVo : importlist) {
					contractItemOperDAO.insertContractItem(contractAndItemVo);
				}
			} else {
				List<ContractItemChange> changelist = transferItemVo2ChangeVo(importlist);
				for (ContractItemChange changevo : changelist) {
					contractItemChangeOperDAO.insertContractItemChange(changevo);
				}
			}
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("合同分项导入失败", e).toString();
		}
		return null;
	}

	private List<ContractItemChange> transferItemVo2ChangeVo(List<ContractAndItemVo> list) {
		List<ContractItemChange> changelist=new ArrayList<ContractItemChange>();
		for (ContractAndItemVo item : list) {
			ContractItemChange changevo = new ContractItemChange();
			changevo.setContractItemId(UUID.randomUUID().toString());
			// changevo.setContractItemId(contractItemId);
			changevo.setContractClauseId(item.getContractClauseId());
			changevo.setContractItemCode(CommonUtil.generateShortUuid());
			changevo.setContractItemName(item.getContractItemName());
			changevo.setContractItemType("10");
			changevo.setContractItemObj("obj");
			changevo.setAmount(item.getAmount());
			changevo.setUnitPrice(item.getUnitPrice());
			changevo.setTotal(item.getItemTotal());
			changevo.setOtherCharge(item.getOtherCharge());
			changevo.setSeriveCharge(new BigDecimal(0));
			changevo.setContItemChangeId(UUID.randomUUID().toString() + "_1");
			changevo.setStatusCd(MDA.CONTRACT_ITEM_CHANGE_STATUS_CD_PENDING.toString());
			changevo.setDescription(item.getDescription());
			changevo.setDataType(MDA.CONTRACT_ITEM_DATA_TYPE_MOFIFY);
			changelist.add(changevo);
		}
		return changelist;
	}
	@Override
	public String deleteContract(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取删除合同签订入参时：";
			String contractId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractId", errorMsg);
			Contract contract = new Contract();
			contract.setContractId(contractId);
			contract.setStatusCd(MDA.CONTRACT_STATUS_CD_CANCELED.toString());
			contractOperDAO.updateContract(contract);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("删除合同签订信息失败", e).toString();
		}
	}

	@Override
	public String deleteContractItem(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取删除合同分项入参时：";
			String conItemId = JsonUtil.getNotNullStringFromJSON(jsonObj, "conItemId", errorMsg);
			String contractItemId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractItemId", errorMsg);
			ContractAndItemVo contractitem = new ContractAndItemVo();
			contractitem.setConItemId(conItemId);
			contractitem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_CANCELED.toString());
			contractItemOperDAO.updateContractItem(contractitem);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("删除合同分项信息失败", e).toString();
		}
	}

	@Override
	public String deleteContractItemChange(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取删除合同分项变更入参时：";
			String contItemChangeId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contItemChangeId", errorMsg);
			String conItemId = JsonUtil.getStringFromJSON(jsonObj, "conItemId", errorMsg);
			if (StringUtil.isNotBlank(contItemChangeId)) {
				ContractItemChange delChangevo = new ContractItemChange();
				delChangevo.setContItemChangeId(contItemChangeId);
				delChangevo.setStatusCd(MDA.CONTRACT_ITEM_CHANGE_STATUS_CD_CANCELED.toString());
				contractItemChangeOperDAO.deleteContractItemChange(delChangevo);
			} else {
				if (StringUtil.isNotBlank(conItemId)) {
					ContractAndItemVo itemVo = new ContractAndItemVo();
					itemVo.setConItemId(conItemId);
					itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_CANCELED.toString());
					contractItemOperDAO.updateContractItem(itemVo);
				}
			}
			// delChangevo =
			// contractItemChangeQueryDAO.queryContractItemChangeDetail(delChangevo);
			// if (contItemChangeId.indexOf("_2") > -1) {
			// delChangevo.setContItemChangeId(contItemChangeId.replace("_2",
			// "_1"));
			// contractItemChangeOperDAO.deleteContractItemChange(delChangevo);
			// }
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("删除合同分项变更信息失败", e).toString();
		}
	}

	@Override
	public String examineContractItem(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取审定合同分项入参时：";
			String type = JsonUtil.getNotNullStringFromJSON(jsonObj, "type", errorMsg);
			String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);
			JSONArray clauseIds = jsonObj.getJSONArray("contractClauseId");
			for (int i = 0; i < clauseIds.size(); i++) {
				String contractClauseId = clauseIds.getString(i);
				// String contractClauseId =
				// JsonUtil.getNotNullStringFromJSON(jsonObj,
				// "contractClauseId", errorMsg);
			ContractAndItemVo contractitem = new ContractAndItemVo();
			contractitem.setContractClauseId(contractClauseId);
			if ("0".equals(type)) {
				contractitem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.toString());
			} else if ("1".equals(type)) {
				contractitem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_UNAPPROVED.toString());
			}
			contractitem.setDescription(description);
				contractItemOperDAO.examineContractItem(contractitem);
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("审定合同分项信息失败", e).toString();
		}
	}

	@Override
	public String examineContractItemChange(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonStr);
			String errorMsg = "获取审定合同分项入参时：";
			String contItemChangeId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contItemChangeId", errorMsg);
			String contractClauseId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractClauseId", errorMsg);
			String conItemId = JsonUtil.getStringFromJSON(jsonObj, "conItemId", errorMsg);
			String type = JsonUtil.getNotNullStringFromJSON(jsonObj, "type", errorMsg);
			// String description = JsonUtil.getStringFromJSON(jsonObj,
			// "description", errorMsg);
			List<ContractItemChange> examinelist = contractItemChangeQueryDAO
					.queryChangeListByContractClauseId(contractClauseId);
			Map<String, List<ContractItemChange>> itemchangemap = new HashMap<String, List<ContractItemChange>>();
			for (ContractItemChange itemChange : examinelist) {
				if (itemchangemap.get(itemChange.getContractItemId()) == null) {
					List<ContractItemChange> changelist = new ArrayList<ContractItemChange>();
					changelist.add(itemChange);
					itemchangemap.put(itemChange.getContractItemId(), changelist);
				} else {
					List<ContractItemChange> changelist = itemchangemap.get(itemChange.getContractItemId());
					changelist.add(itemChange);
					itemchangemap.put(itemChange.getContractItemId(), changelist);
				}
			}
			for (List<ContractItemChange> changelist : itemchangemap.values()) {

			ContractItemChange contractitem = new ContractItemChange();
				contractitem.setContItemChangeId(changelist.get(0).getContItemChangeId().split("_")[0]);
			// 修改变更表记录
			if ("0".equals(type)) {
				contractitem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.toString());
			} else if ("1".equals(type)) {
				contractitem.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_UNAPPROVED.toString());
			}
				contractItemChangeOperDAO.examineContractItemChange(contractitem);
				ContractItemChange examinechangeitem = changelist.get(0);
				ContractAndItemVo itemVo = new ContractAndItemVo();
				if (examinechangeitem.getContItemChangeId().indexOf("_2") > -1) {
					itemVo.setContractItemId(changelist.get(0).getContractItemId());
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("contractItem", itemVo);
					itemVo = contractItemQueryDAO.queryContractItemDetail(param);
					if ("0".equals(type)) {
						// 原记录变为已冲正
						ContractAndItemVo oldcontract = new ContractAndItemVo();
						oldcontract.setConItemId(itemVo.getConItemId());
						oldcontract.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.toString());
						contractItemOperDAO.updateContractItem(oldcontract);
					}
				}
			if ("0".equals(type)) {
					if (examinechangeitem.getContItemChangeId().indexOf("_1") > -1) {
					itemVo.setContractClauseId(examinechangeitem.getContractClauseId());
					itemVo.setConItemId(UUID.randomUUID().toString());
					itemVo.setContractItemObj("obj");// 待确定
					itemVo.setContractItemType("10");
					itemVo.setSeriveCharge(new BigDecimal(0));
					itemVo.setPayment(new BigDecimal(0));
					itemVo.setPaymentRatio(new BigDecimal(0));
					itemVo.setPrepay(new BigDecimal(0));
				}
					if (changelist.size() == 1) {

					// 添加正记录 状态为正常
					itemVo.setAmount(examinechangeitem.getAmount());
					itemVo.setUnitPrice(examinechangeitem.getUnitPrice());
					itemVo.setOtherCharge(examinechangeitem.getOtherCharge());
					itemVo.setDescription(examinechangeitem.getDescription());
					itemVo.setItemTotal(examinechangeitem.getTotal());
					itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.toString());
					itemVo.setCreateDt(examinechangeitem.getCreateDt());
					itemVo.setConItemId(UUID.randomUUID().toString());
						itemVo.setContractItemId(examinechangeitem.getContractItemId());
						itemVo.setContractItemName(examinechangeitem.getContractItemName());
					itemVo.setContractItemCode(CommonUtil.generateShortUuid());
					itemVo.setDataType(examinechangeitem.getDataType());
						itemVo.setUnpaid(new BigDecimal(0));
					contractItemOperDAO.insertContractItem(itemVo);
					// 添加负记录 状态为冲正
						// itemVo.setAmount(examineoldchangeitem.getAmount());
						// itemVo.setUnitPrice(examineoldchangeitem.getUnitPrice());
						// itemVo.setOtherCharge(examineoldchangeitem.getOtherCharge());
						// itemVo.setDescription(examineoldchangeitem.getDescription());
						// itemVo.setItemTotal(examineoldchangeitem.getTotal());
						// itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_CORRECT.toString());
						// itemVo.setCreateDt(examineoldchangeitem.getCreateDt());
						// itemVo.setConItemId(UUID.randomUUID().toString());
						// itemVo.setContractItemCode(CommonUtil.generateShortUuid());
						// itemVo.setDataType(examineoldchangeitem.getDataType());
						// contractItemOperDAO.insertContractItem(itemVo);
				}
					// else if (changelist.size() == 1) {
					// // 添加新记录 状态为正常
					// itemVo.setContractItemId(UUID.randomUUID().toString());
					// itemVo.setAmount(examinechangeitem.getAmount());
					// itemVo.setContractItemName(examinechangeitem.getContractItemName());
					// itemVo.setUnitPrice(examinechangeitem.getUnitPrice());
					// itemVo.setOtherCharge(examinechangeitem.getOtherCharge());
					// itemVo.setDescription(examinechangeitem.getDescription());
					// itemVo.setItemTotal(examinechangeitem.getTotal());
					// itemVo.setUnpaid(examinechangeitem.getTotal());
					// itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.toString());
					// itemVo.setCreateDt(examinechangeitem.getCreateDt());
					// itemVo.setConItemId(UUID.randomUUID().toString());
					// itemVo.setContractItemCode(CommonUtil.generateShortUuid());
					// itemVo.setDataType(examinechangeitem.getDataType());
					// contractItemOperDAO.insertContractItem(itemVo);
					// }
					/*
					 * else if (contItemChangeId.indexOf("_3") > -1) { // 原记录状态
					 * 变成取消 ContractAndItemVo oldcontract = new
					 * ContractAndItemVo(); oldcontract.setConItemId(conItemId);
					 * oldcontract.setStatusCd(MDA.
					 * CONTRACT_ITEM_STATUS_CD_CANCELED.toString());
					 * contractItemOperDAO.updateContractItem(oldcontract); //
					 * 添加新记录 状态为正常 itemVo.setContractItemId(examinechangeitem.
					 * getContractItemId());
					 * itemVo.setAmount(examinechangeitem.getAmount());
					 * itemVo.setUnitPrice(examinechangeitem.getUnitPrice());
					 * itemVo.setOtherCharge(examinechangeitem.getOtherCharge())
					 * ;
					 * itemVo.setDescription(examinechangeitem.getDescription())
					 * ; itemVo.setItemTotal(examinechangeitem.getTotal());
					 * itemVo.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.
					 * toString());
					 * itemVo.setCreateDt(examinechangeitem.getCreateDt());
					 * itemVo.setConItemId(UUID.randomUUID().toString());
					 * itemVo.setContractItemCode(CommonUtil.generateShortUuid()
					 * ); itemVo.setDataType(examinechangeitem.getDataType());
					 * contractItemOperDAO.insertContractItem(itemVo); }
					 */
			} else {
					if (StringUtil.isNotBlank(itemVo.getConItemId())) {
					ContractAndItemVo oldcontract = new ContractAndItemVo();
					oldcontract.setConItemId(itemVo.getConItemId());
					oldcontract.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_UNAPPROVED.toString());
						contractItemOperDAO.updateContractItem(oldcontract);
					}
				/*
				 * if (StringUtil.isNotBlank(conItemId)) { ContractAndItemVo
				 * oldcontract = new ContractAndItemVo();
				 * oldcontract.setConItemId(conItemId);
				 * oldcontract.setStatusCd(MDA.CONTRACT_ITEM_STATUS_CD_APPROVED.
				 * toString());
				 * contractItemOperDAO.updateContractItem(oldcontract); }
				 */
			}
			}
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("审定合同分项信息失败", e).toString();
		}
	}

	@Override
	public String updateBatchContract(String inJson) {
		try {
			String contractIdList = JsonUtil.obtainValueFromJsonObject(inJson, "contractIds");
			String[] contractIds = contractIdList.split(",");
			Map<String, Object> contractMap = new HashMap<String, Object>();
			contractMap.put("contractIds", contractIds);
			contractMap.put("statusCd", Integer.valueOf(JsonUtil.obtainValueFromJsonObject(inJson, "statusCd")));
			contractOperDAO.updateBatchContract(contractMap);
			return ReturnsUtil.returnSuccess(new JSONObject()).toString();
		} catch (BaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getStackTrace());
			}
			return ReturnsUtil.returnFailure(e.getMessage());
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			return ReturnsUtil.returnException("批量审定失败", e).toString();
		}
	}

}
